package com.axzhengxin.platform.sync;

import cn.hutool.core.map.MapUtil;
import cn.hutool.db.Db;
import cn.hutool.db.ds.DSFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.SneakyThrows;
import org.springframework.core.Ordered;

import java.util.Comparator;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * ISyncDataService
 * 新老企业征信中心数据同步服务接口
 *
 * @author jiangnan
 * @date 2021/3/25
 */
public interface ISyncDataService extends Ordered {

    /**
     * 执行方法
     */
    void exec();

    String SQL = "select d1.dept_id, min(u.user_id) as user_id, max(role_id) as role_id " +
            "from sys_dept d1, sys_dept d2, sys_user u, sys_user_role ur " +
            "where (d1.parent_id = d2.dept_id or d1.dept_id = d2.dept_id or d1.ancestors like concat(concat('%', d2.dept_id), '%')) " +
            "and d2.parent_id = 13 and u.dept_id = d2.dept_id and d1.status = 0 and d1.del_flag = 0 and d2.status = 0 and d2.del_flag = 0 " +
            "and ur.user_id = u.user_id and ur.role_id in (26, 27, 28, 30) group by d1.dept_id ";

    @SneakyThrows
    default Map<Long, Long> loadDeptAdminMapper() {
        String profile = SpringUtils.getActiveProfile();
        return Db.use(DSFactory.get(profile))
                .query(SQL)
                .stream()
                .filter(MapUtil::isNotEmpty)
                .map(entity -> entity.toBeanIgnoreCase(SysUser.class))
                .collect(Collectors.toMap(SysUser::getDeptId, SysUser::getUserId,
                        BinaryOperator.minBy(Comparator.comparingLong(deptId -> deptId))));
    }

}
